import { IMenubarIIList, Ifield } from '../type/store/auth';

function deepViewTree(dataHandler: any, data?: Array<IMenubarIIList>): void {
    if (!data || !data.length) return;
    data.forEach((item) => {
        dataHandler(item);
        deepViewTree(dataHandler, item.children);
    });
}

function fieldHandler(item: IMenubarIIList, field: Ifield): void {
    switch (field.name.toLowerCase()) {
    case 'redirect':
        item.redirect = field.description;
        break;
    case 'icon':
        item.meta.icon = field.description;
        break;
    case 'title':
        item.meta.title = field.description;
        break;
    case 'permission':
        item.meta.permission = field.description.split(',');
        break;
    case 'activeMenu':
        item.meta.activeMenu = field.description;
        break;
    case 'noCache':
        item.meta.noCache = field.description === 'true';
        break;
    case 'hidden':
        item.meta.hidden = field.description === 'true';
        break;
    case 'fullscreen':
        item.meta.fullScreen = field.description === 'true';
    }
}

function menuSort(menu: IMenubarIIList): void {
    if (!menu.children) return;
    menu.children?.sort((a, b) => (a.sortIndex || 0) - (b.sortIndex || 0));
}

/**
 * list结构转tree
 * @param data list原始数据
 * @param sign 菜单标识
 */
export function authMenuTree(
    data: Array<IMenubarIIList>,
    sign: string
): Array<IMenubarIIList> {
    const menu = data.find((x) => x.sign === sign);
    if (!menu) return [];
    menuSort(menu);
    deepViewTree((item: IMenubarIIList) => {
        item.meta = item.meta || { icon: '', title: '' };
        item.url && (item.path = item.url);
        item.path = item.path || '/';
        item.icon && (item.meta.icon = item.icon as string);
        if (item.sign) {
            item.meta.title = item.name;
            item.name = item.sign;
        }
        item.fields?.forEach((field) => fieldHandler(item, field));
        menuSort(item);
    }, menu.children);
    return menu.children || [];
}
